<script>
import { defineComponent } from 'vue'
import { mapActions, mapState } from 'vuex'
import conversationService from '@/service/conversationService'
import folderService from '@/service/folderService'

export default defineComponent({
  name: 'ConversationImport',
  data() {
    return {
      loadTokenCount: 0,

      /**
       * NO_IMPORTED: 未导入
       * WAIT_TOKEN: 等待token
       * NO_TOKEN: 没有token
       * FETCHING: 正在获取会话
       * IMPORTING: 正在导入
       * IMPORT_SUCCESS: 导入成功
       * IMPORT_FAILED: 导入失败
       */
      importStatus: 'NO_IMPORTED',

      processor: {
        total: -1,
        current: 0,
      },
    }
  },
  methods: {
    ...mapActions({
      resetAndClear: 'resetAndClear',
      setIsImport: 'system/setIsImport',
    }),

    /**
     * 点击导入会话
     */
    onImportConversations() {
      // 检查chrome.storage.local中是否有有chatGptToken
      chrome.storage.local.get(['chatGptToken'], result => {
        if (!result.chatGptToken) {
          // 去查询是否有打开chatgpt页面，如果有，就刷新一下。然后等待一会儿可能就能获取到token
          // 如果用户没有登录，或者没有打开chatgpt页面，就引导用户去登录或者打开chatgpt页面刷新
          chrome.tabs.query({ url: 'https://chat.openai.com/*' }, tabs => {
            // 如果有打开https://chat.openai.com/，就刷新页面
            if (tabs.length && !tabs[0].url.endsWith('/auth/login')) {
              this.importStatus = 'WAIT_TOKEN'

              // 刷新页面当前tab
              chrome.tabs.reload(tabs[0].id)
              this.loadToken()
            } else {
              this.importStatus = 'NO_TOKEN'
            }
          })
        } else {
          this.doImport()
        }
      })
    },

    /**
     * 如果发起了refreshPage，那么就需要重新加载token
     */
    loadToken() {
      if (this.importStatus !== 'WAIT_TOKEN') {
        return
      }

      // 每0.5秒检查一次chrome.storage中是否有token，如果有，调用doImport
      // loadTokenCount用来记录检查的次数，如果超过60次，就不再检查了
      // 即如果超时后还没有token，那么将状态改为NO_TOKEN
      if (this.loadTokenCount < 60 && this.importStatus === 'WAIT_TOKEN') {
        this.loadTokenCount += 1

        chrome.storage.local.get(['chatGptToken'], result => {
          if (result.chatGptToken) {
            this.doImport()
          } else {
            setTimeout(() => {
              this.loadToken()
            }, 500)
          }
        })
      } else {
        this.importStatus = 'NO_TOKEN'
      }
    },
    goLogin() {
      chrome.tabs.create({ url: 'https://chat.openai.com' })
    },

    /**
     * 导入会话
     */
    async doImport() {
      this.importStatus = 'IMPORTING'

      // 清空并重置store中的数据, 确保导入的时候，数据是干净的
      await this.resetAndClear()

      conversationService.fetchApiAll()
        .then(async res => {
          const { success, data } = res
          if (success) {
            // 如果没有会话，直接导入成功
            if (!data.length) {
              this.importStatus = 'IMPORT_SUCCESS'
              await this.setIsImport()

              return
            }

            // 创建默认的unsorted目录
            await folderService.createDefaultFolder()
            await conversationService.addBatch(data)
            const conversationIds = data.map(item => item.id)

            // 发送消息给background，添加到队列
            chrome.runtime.sendMessage({
              target: 'background',
              action: 'addToQueue',
              params: {
                conversationIds,
              },
            })

            // if (this.processor.current === this.processor.total && this.importStatus === 'IMPORTING') {
            this.importStatus = 'IMPORT_SUCCESS'

            await this.setIsImport()

            // }
          } else {
            await this.resetAndClear()
            this.importStatus = 'IMPORT_FAILED'
          }
        }).catch(() => {
          this.resetAndClear()
          this.importStatus = 'IMPORT_FAILED'
        })
    },
  },
  computed: {
    ...mapState({
      /**
       * 是否初始化
       */
      isImport: state => state.system.isImport,
    }),
  },
  mounted() {
    chrome.storage.local.get(['chatGptToken'], result => {
      if (!result.chatGptToken) {
        this.importStatus = 'NO_TOKEN'
      }
    })
  },
})
</script>

<template>
  <div>
    <!-- 如果没有导入，引导用户进行导入 -->
    <v-sheet
      v-if="importStatus === 'NO_IMPORTED'"
      width="100%"
      class="pa-4 text-center mx-auto"
    >

      <h2 class="text-h5 mb-6">Welcome to ChatGPT Conversation Manager!</h2>

      <p class="mb-4 text-medium-emphasis text-body-2">
        Ready to launch your ChatGPT experience to the next level? 🚀
        Just hit the button below to sync your conversations.
        You're just one click away from organizing all those amazing conversations.
        Let's hit the button and celebrate! 🎉
      </p>

      <div class="text-center">
        <v-btn
          class="text-none"
          color="teal-lighten-2"
          @click="onImportConversations"
        >
          Import Conversations
        </v-btn>
      </div>
    </v-sheet>

    <!-- 否则，如果是等待页面刷新的，则提示等待刷新 -->
    <v-sheet
      v-else-if="importStatus === 'WAIT_TOKEN'"
      width="100%"
      class="pa-4 text-center mx-auto"
    >
      <h2 class="text-h5 mb-6">Connecting to ChatGPT...</h2>
      <p class="mb-4 text-medium-emphasis text-body-2">
        Hold your tea! ☕️ We're bridging the conversation gap! 🚀
      </p>
      <div class="text-center">
        <v-progress-circular
          indeterminate
          color="teal"
        ></v-progress-circular>
      </div>
    </v-sheet>

    <!-- 否则，如果是正在导入的，则显示导入进度 -->
    <v-sheet
      v-else-if="importStatus === 'IMPORTING'"
      width="100%"
      class="pa-4 text-center mx-auto"
    >
      <h2 class="text-h5 mb-6">Importing Your Conversations...</h2>
      <p class="mb-4 text-medium-emphasis text-body-2">
        Hang tight! 😊 Your conversations are jetting over...🚀
        Please keep this page open, or else the conversations might get lost in space! 🌌
        Relax and grab a cup of tea while we take care of everything else. ☕️
      </p>
      <div class="text-center">
        <v-progress-circular
          v-if="processor.total < 0"
          indeterminate
          color="teal"
        ></v-progress-circular>
        <v-progress-circular
          v-else
          :rotate="360"
          :size="120"
          :width="15"
          :model-value="(processor.current / processor.total) * 100"
          color="teal"
        >
          {{ processor.current }} / {{ processor.total }}
        </v-progress-circular>
      </div>
    </v-sheet>

    <!-- 否则，如果如果是需要登录的 -->
    <v-sheet
      v-else-if="importStatus === 'NO_TOKEN'"
      width="100%"
      class="pa-4 text-center mx-auto"
    >
      <h2 class="text-h5 mb-6">Oops, We Hit a Small Bump! 🧐</h2>
      <p class="mb-4 text-medium-emphasis text-body-2">
        It seems you haven't logged in or opened a ChatGPT page yet! Quick,
        jet over to 🚀<a href="https://chat.openai.com">https://chat.openai.com</a>
        and then come back here! 😊
      </p>
      <div class="text-center">
        <v-btn
          class="text-none"
          color="teal-lighten-2"
          variant="flat"
          @click="goLogin"
        >
          Blast off to ChatGPT! 🚀
        </v-btn>
      </div>
    </v-sheet>
    <!-- 否则，如果如果是需要登录的 -->
    <v-sheet
      v-else-if="importStatus === 'IMPORT_FAILED'"
      width="100%"
      class="pa-4 text-center mx-auto"
    >
      <h2 class="text-h5 mb-6">Oops, we hit a snag... 🚧</h2>
      <p class="mb-4 text-medium-emphasis text-body-2">
        It seems like your conversations are playing hide and seek! 🙈 Let's try again, shall we? 😊
      </p>
      <div class="text-center">
        <v-btn
          class="text-none"
          color="teal-lighten-2"
          variant="flat"
          @click="onImportConversations"
        >
          Retry Import
        </v-btn>
      </div>
    </v-sheet>

  </div>
</template>

<style scoped>

</style>
